package com.hhhn.wk.main.fragment;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseFragment;
import com.hhhn.wk.config.Config;
import com.hhhn.wk.entity.User;
import com.hhhn.wk.main.MainActivity;
import com.hhhn.wk.main.tab1.MoreCommodityListActivity;
import com.hhhn.wk.main.tab1.banner.Banner;
import com.hhhn.wk.main.tab1.SearchActivity;
import com.hhhn.wk.main.tab1.notice.Notice;
import com.hhhn.wk.main.tab1.notice.NoticeListActivity;
import com.hhhn.wk.main.tab1.typeclass.TypeClass;
import com.hhhn.wk.main.tab2.entity.Commodity;
import com.hhhn.wk.main.tab2.view.CommodityListActivity;
import com.hhhn.wk.main.tab2.view.xiangqing.activity.CommodityXQActivity;
import com.hhhn.wk.main.tab4.address.entity.Address;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.utils.SharePreferencesUser;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.banner.AdViewpagerUtil;
import com.hhhn.wk.widget.customview.BottomScrollView;
import com.hhhn.wk.widget.customview.MyListView;
import com.hhhn.wk.widget.customview.ObservableScrollView;
import com.hhhn.wk.widget.customview.PullToRefreshView;
import com.hhhn.wk.widget.wkpulltorefreshlayout.PullToRefreshLayout;
import com.superluo.textbannerlibrary.ITextBannerItemClickListener;
import com.superluo.textbannerlibrary.TextBannerView;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.nio.file.WatchKey;
import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;
import static com.hhhn.wk.utils.AllPublic.isHuoNiu;

/**
 * A simple {@link Fragment} subclass.
 */
public class TabFragment01 extends BaseFragment implements PullToRefreshView.OnHeaderRefreshListener, PullToRefreshView.OnFooterRefreshListener {
//    private PullToRefreshView mPullToRefreshView;
    private boolean isWu=false;
    TextBannerView tvBanner ;


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = null;

    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private LinearLayout ll_top;//回到顶部
    private static final String TAG = "TabFragment01";
    //搜索
    private LinearLayout ll_search;
    /*banner*/
    private ViewPager viewpager;
    private LinearLayout lydots;
    private AdViewpagerUtil adViewpagerUtil;
    private ArrayList<Banner> mBanner=new ArrayList<>();
    //滚动
    private BottomScrollView mObservableScrollView;
    private RelativeLayout mTextView;
    private LinearLayout mHeaderContent;
    private int mHeight;
    //GridView热销
    private GridView mHostGridView;
    private MyAdaper<Commodity> mHostyAdaper;
    private ArrayList<Commodity> mHostArrayList=new ArrayList<>();
    private LinearLayout ll_more;//更多热销
    private int pageHot=1;
    //特价抢购
    private LinearLayout ll_moreRush;
    private MyListView mListViewRush;
    private MyAdaper<Commodity> mRushAdaper;
    private ArrayList<Commodity> mRushArrayList=new ArrayList<>();
    private TextView tv_dingWei;//定位
    //精选分类
    private GridView mGridView5;
    private MyAdaper<TypeClass> mTypeClassMyAdaper;
    private ArrayList<TypeClass> mTypeClassArrayList=new ArrayList<>();
    //公告通知
    List<String> mNoticeList = new ArrayList<>();
    LinearLayout ll_notice;
    //货牛专供
    MBroadcastReceiver mBroadcastReceiver;//广播接受者
    private GridView mLoadListViewhuoniu;
    public static ArrayList<Commodity> mArrayListhuoniu=new ArrayList<Commodity>();
    private static MyAdaper<Commodity> mAdapterhuoniu;
    private LinearLayout ll_zhuangong;
    Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what){
                    case 1://更多热销
                        dataHost();
                        break;
                    case 2://特价抢购
                        dataRush();
                        break;
                    case 3://baner
                        dataBanner();
                        break;
                    case 4://获取定位
                        dataAdress();
                        break;
                    case 5://获取精选分类
                        dataclass();
                        break;
                    case 6://获取公告
                        dataNotice();
                        break;
                    case 7://货牛专供
                        loadDatahuoniu();
                        break;
                }
            }
        };
    private void dataAdress() {
        gaode();
    }
    public TabFragment01() {}
    @Override
    protected int setLayoutResouceId() {
        return R.layout.fragment_tab_fragment01;
    }
    @Override
    protected void initView(View mRootView) {
        mLoadListViewhuoniu = findViewById(R.id.mGridView7);
        ll_zhuangong = findViewById(R.id.ll_zhuangong);
        ll_notice = findViewById(R.id.ll_notice);
        tvBanner = findViewById(R.id.tv_banner);
        mGridView5 = mRootView.findViewById(R.id.mGridView5);
        tv_dingWei = mRootView.findViewById(R.id.tv_dingWei);
        ll_top = mRootView.findViewById(R.id.ll_top);
        ll_search = mRootView.findViewById(R.id.ll_header_content);
        mListViewRush = mRootView.findViewById(R.id.mListViewRush);
        ll_moreRush = mRootView.findViewById(R.id.ll_moreRush);
        ll_more = mRootView.findViewById(R.id.ll_more);
        mHostGridView = mRootView.findViewById(R.id.mGridView);
        viewpager = mRootView.findViewById(R.id.viewpager);
        lydots = mRootView.findViewById(R.id.ly_dots);
        mObservableScrollView = findViewById(R.id.sv_main_content);
        mTextView = findViewById(R.id.rl_adroot);
        mHeaderContent = (LinearLayout) findViewById(R.id.ll_header_content);
//        mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
//        mPullToRefreshView.setOnHeaderRefreshListener(this);
//        mPullToRefreshView.setOnFooterRefreshListener(this);

    }
    @Override
    protected void initData() {
        mBroadcastReceiver = new MBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        //设置接收广播的类型
        intentFilter.addAction(Constants.MBroadcastReceiverCart);
        //调用Context的registerReceiver（）方法进行动态注册
        mActivity.registerReceiver(mBroadcastReceiver, intentFilter);
        mObservableScrollView.setOnScrollToBottomLintener(new BottomScrollView.OnScrollToBottomListener() {

            @Override
            public void onScrollBottomListener(boolean isBottom) {
                // TODO Auto-generated method stub
                Log.e("SCROLLVIEW", isBottom + "");
                if(isBottom){
                 /* 上拉加载更多 */
                    h.sendEmptyMessage(1);
                }
            }
        });
//        //获取标题栏高度
//        ViewTreeObserver viewTreeObserver = mTextView.getViewTreeObserver();
//        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                mTextView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                mHeight = mTextView.getHeight() - mHeaderContent.getHeight();//这里取的高度应该为图片的高度-标题栏
//                //注册滑动监听
//                mObservableScrollView.setOnObservableScrollViewListener(new OnObservableScrollViewListener() {
//                    @Override
//                    public void onObservableScrollViewListener(int l, int t, int oldl, int oldt) {
//                        if (t <= 0) {
//                            //顶部图处于最顶部，标题栏透明
//                            mHeaderContent.setBackgroundColor(Color.argb(0, 48, 63, 159));
//                            ll_top.setVisibility(View.GONE);
//                        } else if (t > 0 && t < mHeight) {
//                            //滑动过程中，渐变
//                            float scale = (float) t / mHeight;//算出滑动距离比例
//                            float alpha = (255 * scale);//得到透明度
//                            mHeaderContent.setBackgroundColor(Color.argb((int) alpha, 236, 15, 56));
//                            ll_top.setVisibility(View.GONE);
//                        } else {
//                            //过顶部图区域，标题栏定色
//                            mHeaderContent.setBackgroundColor(Color.argb(255, 236, 15, 56));
//                            ll_top.setVisibility(View.VISIBLE);
//                        }
//                    }
//                });
//            }
//        });
        mActivity.showLoad();
        getBanner();
        getHotJSON();
        getSpecial();
        getTypeClass();
        getNotice();
        getJSONhuoniu();
        handler.sendEmptyMessage(4);
    }
    @Override
    protected void initClick() {
        //回到顶部
        ll_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mObservableScrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        mObservableScrollView.fullScroll(ScrollView.FOCUS_UP);
                    }
                });
            }
        });
        //热销
        mHostGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(mActivity,CommodityXQActivity.class);
                startActivity(intent);
            }
        });
        //更多热销
        ll_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mActivity,MoreCommodityListActivity.class);
//                intent.putExtra("title","热销产品");
                intent.putExtra("type",0);
                startActivity(intent);
            }
        });
        //特价抢购
        ll_moreRush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mActivity,MoreCommodityListActivity.class);
//                intent.putExtra("title","特价抢购");
                intent.putExtra("type",1);
                startActivity(intent);
            }
        });
        //搜索
        ll_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(mActivity,SearchActivity.class);
                startActivity(intent);
            }
        });
        mHostGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(mActivity,CommodityXQActivity.class);
                intent.putExtra("goods_id",mHostArrayList.get(i).getCommodityID());
                startActivity(intent);
            }
        });
        mListViewRush.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mRushArrayList.get(i).getInventoryNumber()!=null&&!mRushArrayList.get(i).getInventoryNumber().equals("")){
                    int kk = Integer.parseInt(mRushArrayList.get(i).getInventoryNumber());
                    if (kk==0||kk<0){
                         toastWk("您来晚了！");
                    }else {
                        Intent intent=new Intent(mActivity,CommodityXQActivity.class);
                        intent.putExtra("goods_id",mRushArrayList.get(i).getCommodityID());
                        startActivity(intent);
                    }
                }
            }
        });
        mGridView5.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //跳转到 二级分类 列表页面
                Intent intent = new Intent(getActivity(), CommodityListActivity.class);
                intent.putExtra("title_str", mTypeClassArrayList.get(i).getTitle());
                intent.putExtra("categoryTwo", mTypeClassArrayList.get(i).getId());
                startActivity(intent);
            }
        });
        mLoadListViewhuoniu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent=new Intent(mActivity,CommodityXQActivity.class);
                intent.putExtra("goods_id",mArrayListhuoniu.get(i).getCommodityID());
                startActivity(intent);
            }
        });
        ll_notice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mActivity, NoticeListActivity.class));
            }
        });
        //专供
        ll_zhuangong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(mActivity,CommodityListActivity.class);
                intent.putExtra("title_str","货牛专供");
                intent.putExtra("categoryTwo","171");
                startActivity(intent);
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHostArrayList!=null){
            mHostArrayList.clear();
        }
        if (mArrayListhuoniu!=null){
            mArrayListhuoniu.clear();
        }
        if (mTypeClassArrayList!=null){
            mTypeClassArrayList.clear();
        }
        if (mNoticeList!=null){
            mNoticeList.clear();
        }
        if (mHostyAdaper!=null){
            mHostyAdaper=null;
        }
        if (mTypeClassMyAdaper!=null){
            mTypeClassMyAdaper=null;
        }
        if (mAdapterhuoniu!=null){
            mAdapterhuoniu=null;
        }
    }
    //获取公告
    private void getNotice(){
        RequestParams params = AllPublic.getParamsDynamic(mActivity, "/dynamicList", false);
        params.addParameter("currentPage",pageHot);
        params.addParameter("pageSize",10);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("##", "获取公告: "+result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        for (int i=0;i<data.length();i++){
                            JSONObject object = data.getJSONObject(i);
                            String title = object.has("title") ? object.getString("title") : "";
                            mNoticeList.add(title);
                        }
                        handler.sendEmptyMessage(6);
                    }else {
                        Toast.makeText(mActivity,jsonObject.getString("errMsg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }
    //加载公告
   private void dataNotice(){
//调用setDatas(List<String>)方法后,TextBannerView自动开始轮播
//注意：此方法目前只接受List<String>类型
       tvBanner.setDatas(mNoticeList);

// Drawable drawable = getResources().getDrawable(R.mipmap.logo_niu);
///**这里可以设置带图标的数据（1.0.2新方法），比setDatas方法多了带图标参数；
// 第一个参数：数据 。
// 第二参数：drawable.
// 第三参数:drawable尺寸。
// 第四参数:图标位置仅支持Gravity.LEFT、Gravity.TOP、Gravity.RIGHT、Gravity.BOTTOM
// */
//       tvBanner.setDatasWithDrawableIcon(mNoticeList,drawable,18, Gravity.LEFT);
//
////设置TextBannerView点击监听事件，返回点击的data数据, 和position位置
//       tvBanner.setItemOnClickListener(new ITextBannerItemClickListener() {
//           @Override
//           public void onItemClick(String data, int position) {
//               Log.i("点击了：",String.valueOf(position)+">>"+data);
//           }
//       });
   }
    //获取banner
    public void getBanner() {
        RequestParams params = AllPublic.getParamsBanner(mActivity, "/getBanner", false);
//        Log.d(TAG, "获取banner: "+params);
       User user = (User) SharePreferencesUser.getBean(mActivity, Constants.USER);
        if (user!=null){
            int isLogin = user.getIsLogin();
            if (isLogin==2){
                params.addParameter("merchantId",user.getUid());
            }else {
                params.addParameter("merchantId","");
            }
        }else {
            params.addParameter("merchantId","");
        }
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
//                mActivity. LogWk("获取banner:"+result);
                Log.d(TAG, "获取banner: "+result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        Banner banner=null;
                        for (int i=0;i<data.length();i++){
                            banner=new Banner();
                            JSONObject object = data.getJSONObject(i);
                            String id = object.has("id") ? object.getString("id") : "";
                            String webUrl = object.has("webUrl") ? object.getString("webUrl") : "";
                            String appUrl = object.has("appUrl") ? object.getString("appUrl") : "";
                            String image = object.has("image") ? object.getString("image") : "";
                            String type = object.has("type") ? object.getString("type") : "";
                            String title = object.has("title") ? object.getString("title") : "";
                            banner.setAppurl(appUrl);
                            banner.setId(id);
                            banner.setWebUrl(webUrl);
                            banner.setImage(image);
                            banner.setType(type);
                            banner.setTitle(title);
                            mBanner.add(banner);
                            handler.sendEmptyMessage(3);
                        }
                    }else {
                        Toast.makeText(mActivity,jsonObject.getString("errMsg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
            }
            @Override
            public void onFinished() {
            }
        });
    }
    //加载banner
    private void dataBanner(){
        String[] urls = new String[mBanner.size()];
        for (int i=0;i<mBanner.size();i++){
            urls[i] =mBanner.get(i).getImage();
        }
        adViewpagerUtil = new AdViewpagerUtil(mActivity, viewpager, lydots, 6, 2, urls);
        adViewpagerUtil.initVps();
        adViewpagerUtil.setOnAdItemClickListener(new AdViewpagerUtil.OnAdItemClickListener() {
            @Override
            public void onItemClick(View v, int flag) {
                AllPublic.bannerURL(mActivity,mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl(),mBanner.get(flag).getAppurl());
//                switch (flag){
//                    case 0:
//                        try {
//                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
//                        } catch (Exception ignored) {
//                            toastWk( ignored + "");
//                        }
//                        break;
//                    case 1:
//                        try {
//                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
//                        } catch (Exception ignored) {
//                            toastWk( ignored + "");
//                        }
//                        break;
//                    case 2:
//                        try {
//                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
//                        } catch (Exception ignored) {
//                            toastWk( ignored + "");
//                        }
//                       break;
//                    case 3:
//                        try {
//                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
//                        } catch (Exception ignored) {
//                            toastWk( ignored + "");
//                        }
//                       break;
//                    case 4:
//                        try {
//                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
//                        } catch (Exception ignored) {
//                            toastWk( ignored + "");
//                        }
//                       break;
//                    case 5:
//                        try {
//                            AllPublic.linkH5(mActivity, mActivity,mBanner.get(flag).getTitle(),mBanner.get(flag).getWebUrl());
//                        } catch (Exception ignored) {
//                            toastWk( ignored + "");
//                        }
//                        break;
//                }
            }
        });
    }
    //获取热销产品
    public void getHotJSON() {
        RequestParams params = AllPublic.getParamsProduct(mActivity, "/hotProduct", false);
        params.addParameter("currentPage",pageHot);
        params.addParameter("pageSize",4);
//        Log.d("获取热销产品", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("获取热销产品：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Commodity commodity=null;
//                        Log.d(TAG, "onSuccess: "+records.length());
                        if (records.length()<10){
                            isWu=true;
                        }
                        for (int i=0;i<records.length();i++){
                            commodity=new Commodity();
                            JSONObject object = records.getJSONObject(i);

                            String commodityid = object.has("id") ? object.getString("id") : "";//id
                            String image = object.has("productPicture") ? object.getString("productPicture") : "";//产品图片
                            String headLine = object.has("name") ? object.getString("name") : "";//产品名称
                            String tradeprice = object.has("wholesalePriceThree") ? object.getString("wholesalePriceThree") : "";//新价格-折扣价格
                            String originalprice = object.has("originalPrice") ? object.getString("originalPrice") : "";//原价-旧价格
                            String inventory = object.has("inventory") ? object.getString("inventory") : "";//商品库存-剩余库存
                            commodity.setCommodityID(commodityid);
                            commodity.setCommodityImg(image);
                            commodity.setCommodityName(headLine);
                            commodity.setPriceOld(originalprice);
                            commodity.setPriceNew(tradeprice);
                            commodity.setInventoryNumber(inventory);
                            mHostArrayList.add(commodity);
                        }
                        handler.sendEmptyMessage(1);
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();

            }
            @Override
            public void onCancelled(CancelledException cex) {


            }
            @Override
            public void onFinished() {


            }
        });
    }
    //加载热销产品
    private void dataHost() {
//        // item宽度
//        int itemWidth = DensityUtil.dip2px(200);
//        // item之间的间隔
//        int itemPaddingH = DensityUtil.dip2px(1);
//        int size = mHostArrayList.size();
//        // 计算GridView宽度
//        int gridviewWidth = size * (itemWidth + itemPaddingH);
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
//                gridviewWidth, LinearLayout.LayoutParams.MATCH_PARENT);
//        mHostGridView.setLayoutParams(params);
//        mHostGridView.setColumnWidth(itemWidth);
//        mHostGridView.setHorizontalSpacing(itemPaddingH);
//        mHostGridView.setStretchMode(GridView.NO_STRETCH);
//        mHostGridView.setNumColumns(size);
        if (mHostyAdaper==null){
            mHostyAdaper=new MyAdaper<Commodity>(mHostArrayList,R.layout.item_commoditylist) {
                @Override
                public void bindView(ViewHolder holder, Commodity obj, int position) {
                    holder.setImagechang(R.id.iv_CommodityImg,obj.getCommodityImg());//图片
                    holder.setText(R.id.iv_CommodityName,obj.getCommodityName());

                    if (isHuoNiu(mActivity)){
                        holder.setText(R.id.tv_priceNew,"￥"+obj.getPriceNew());
                        holder.setFlags(R.id.tv_priceOld,"￥"+obj.getPriceOld());
                    }else {
                        holder.setText(R.id.tv_priceNew,"￥?");
                        holder.setFlags(R.id.tv_priceOld,"￥?");
                    }

                    holder.setText(R.id.tv_inventoryNumber,"剩余："+obj.getInventoryNumber());
                }
            };
        }else {
            mHostyAdaper.notifyDataSetChanged();
        }
        mHostGridView.setAdapter(mHostyAdaper);
//        mPullToRefreshView.onFooterRefreshComplete();
//        mPullToRefreshView.onHeaderRefreshComplete();
        mActivity.dismissLoad();
    }
    //获取特价商品
    private void getSpecial(){
        RequestParams params = AllPublic.getParamsProduct(mActivity, "/special", false);
        params.addParameter("currentPage",pageHot);
        params.addParameter("pageSize",3);
//        Log.d("获取特价商品", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
//                Log.d("获取特价商品：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Commodity commodity=null;
                        for (int i=0;i<records.length();i++){
                            commodity=new Commodity();
                            JSONObject object = records.getJSONObject(i);
                            String commodityid = object.has("id") ? object.getString("id") : "";//id
                            String image = object.has("productPicture") ? object.getString("productPicture") : "";//产品图片
                            String headLine = object.has("name") ? object.getString("name") : "";//产品名称
                            String tradeprice = object.has("wholesalePriceThree") ? object.getString("wholesalePriceThree") : "";//新价格-折扣价格
                            String originalprice = object.has("originalPrice") ? object.getString("originalPrice") : "";//原价-旧价格
                            String inventory = object.has("inventory") ? object.getString("inventory") : "";//商品库存-剩余库存
                            commodity.setCommodityID(commodityid);
                            commodity.setCommodityImg(image);
                            commodity.setCommodityName(headLine);
                            commodity.setPriceOld(originalprice);
                            commodity.setPriceNew(tradeprice);
                            commodity.setInventoryNumber(inventory);
                            mRushArrayList.add(commodity);
                        }
                        handler.sendEmptyMessage(2);
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();

            }
            @Override
            public void onCancelled(CancelledException cex) {


            }
            @Override
            public void onFinished() {


            }
        });
    }
    //加载特价
    private void dataRush() {
        if (mRushAdaper==null){
            mRushAdaper=new MyAdaper<Commodity>(mRushArrayList,R.layout.item_conlist_rush) {
                @Override
                public void bindView(ViewHolder holder, final Commodity obj, int position) {
                    holder.setImagechang(R.id.iv_CommodityImg,obj.getCommodityImg());//图片
                    holder.setText(R.id.iv_CommodityName,obj.getCommodityName());

                    if (isHuoNiu(mActivity)){
                        holder.setText(R.id.tv_priceNew,"￥"+obj.getPriceNew());
                        holder.setFlags(R.id.tv_priceOld,"￥"+obj.getPriceOld());
                    }else {
                        holder.setText(R.id.tv_priceNew,"￥?");
                        holder.setFlags(R.id.tv_priceOld,"￥?");
                    }

                    holder.setText(R.id.tv_shengyu,"剩余："+obj.getInventoryNumber());
                    if (obj.getInventoryNumber()!=null&&!obj.getInventoryNumber().equals("")){
                        int i = Integer.parseInt(obj.getInventoryNumber());
                        if (i==0||i<0){
                            holder.setImageResource(R.id.mImageView,R.mipmap.go_qiang_p);
                        }else {
                            holder.setImageResource(R.id.mImageView,R.mipmap.go_qiang);
                        }
                    }

                }
            };
        }else {
            mRushAdaper.notifyDataSetChanged();
        }
        mListViewRush.setAdapter(mRushAdaper);

    }
    //加载精选分类
    private void getTypeClass(){
        RequestParams params = AllPublic.getParamsType(mActivity, "/homePageType", false);
        params.addParameter("currentPage",1);
        params.addParameter("pageSize",100);
//        Log.d("加载精选分类", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("加载精选分类：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        JSONArray records = data.getJSONArray("appType");
                        TypeClass mTypeClass=null;

//                        int max=0;
//                        if (records.length()>5){
//                            max=5;
//                        }else {
//                            max=records.length();
//                        }
                        for (int i=0;i<records.length();i++){
                            mTypeClass=new TypeClass();

                            JSONObject object = records.getJSONObject(i);
                            String itemId = object.has("itemId") ? object.getString("itemId") : "";//id
                            String name = object.has("twoName") ? object.getString("twoName") : "";//
                            String picture = object.has("picture") ? object.getString("picture") : "";//

                            mTypeClass.setId(itemId);
                            mTypeClass.setTitle(name);
                            mTypeClass.setImg(picture);
                            Log.d(TAG, "onSuccess: "+picture);
                            mTypeClassArrayList.add(mTypeClass);
                        }
                        handler.sendEmptyMessage(5);
                    }else {
                        mActivity.toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();

            }
            @Override
            public void onCancelled(CancelledException cex) {


            }
            @Override
            public void onFinished() {


            }
        });


    }
    //获取精选分类
    private void dataclass() {
        if (mTypeClassMyAdaper==null){
            mTypeClassMyAdaper=new MyAdaper<TypeClass>(mTypeClassArrayList,R.layout.item_conlist_typeclass) {
                @Override
                public void bindView(ViewHolder holder, final TypeClass obj, int position) {
                    holder.setImagechang(R.id.iv_CommodityImg,obj.getImg());//图片
                    holder.setText(R.id.iv_CommodityName,obj.getTitle());
                    Log.e(TAG, "获取精选分类: "+  Constants.HTTPIMG+obj.getImg()+"");
                }
            };
        }else {
            mTypeClassMyAdaper.notifyDataSetChanged();
        }
        mGridView5.setAdapter(mTypeClassMyAdaper);
    }
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
//        if (isWu){
//            toastWk("暂无更多热销商品");
//            mPullToRefreshView.onFooterRefreshComplete();
//        }else {
//            /* 上拉加载更多 */
//            h.sendEmptyMessage(1);
//        }

    }
    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
		/* 下拉刷新数据 */
        h.sendEmptyMessage(2);
    }
    Handler h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
//                pageHot++;
//                getHotJSON();
            } else if (msg.what == 2) {
//                h.postAtTime(new Runnable() {
//                    @Override
//                    public void run() {
//                        mPullToRefreshView.onHeaderRefreshComplete();
//                    }
//                }, SystemClock.uptimeMillis() + 1000);
                isWu=false;
                pageHot=1;
                if (mHostArrayList!=null){
                    mHostArrayList.clear();
                }
                if (mRushArrayList!=null){
                    mRushArrayList.clear();
                }
                if (mTypeClassArrayList!=null){
                    mTypeClassArrayList.clear();
                }
                if (mNoticeList!=null){
                    mNoticeList.clear();
                }
                if (mArrayListhuoniu!=null){
                    mArrayListhuoniu.clear();
                }
                getHotJSON();
                getSpecial();
                getTypeClass();
                getNotice();
                getJSONhuoniu();
            }
        };
    };
    public class MBroadcastReceiver extends BroadcastReceiver {
        //接收到广播后自动调用该方法
        @Override
        public void onReceive(Context context, Intent intent) {
            //写入接收广播后的操作
//            Log.d(TAG, "MBroadcastReceiver: 接收广播");
            handler.sendEmptyMessage(1);
            handler.sendEmptyMessage(2);
            handler.sendEmptyMessage(7);
        }
    }
    private void gaode(){
        //初始化定位
        mLocationClient = new AMapLocationClient(mActivity.getApplicationContext());
        mLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                        aMapLocation.getLatitude();//获取纬度
//                        aMapLocation.getLongitude();//获取经度
//                        aMapLocation.getAccuracy();//获取精度信息
//                        aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                        aMapLocation.getCountry();//国家信息
//                        aMapLocation.getProvince();//省信息
                        aMapLocation.getCity();//城市信息
                        aMapLocation.getDistrict();//城区信息
//                        aMapLocation.getStreet();//街道信息
//                        aMapLocation.getStreetNum();//街道门牌号信息
//                        aMapLocation.getCityCode();//城市编码
//                        aMapLocation.getAdCode();//地区编码
//                        aMapLocation.getAoiName();//获取当前定位点的AOI信息
//                        aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                        aMapLocation.getFloor();//获取当前室内定位的楼层
//                        aMapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
                        //获取定位时间
//                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        Date date = new Date(aMapLocation.getTime());
//                        df.format(date);
//                       mActivity. getMyApp().setStr_adress(aMapLocation.getCity());
                        tv_dingWei.setText(aMapLocation.getDistrict()+"");
//                        Log.d("定位：", "城市信息: "+aMapLocation.getCity());
//                        Log.d("定位：", "城区信息: "+aMapLocation.getDistrict());

//                        Log.d("定位：", "获取GPS的当前状态: "+aMapLocation.getGpsAccuracyStatus());
//                        Log.d("定位：", "获取当前室内定位的楼层: "+aMapLocation.getFloor());
                        toastWk(aMapLocation.getCity());
                    }else {
//                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                        Log.e("AmapError","location Error, ErrCode:"
//                                + aMapLocation.getErrorCode() + ", errInfo:"
//                                + aMapLocation.getErrorInfo());
                    }
                }
            }
        };
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }
    /**
     * 货牛专供
     *
     */
    public void getJSONhuoniu() {
        RequestParams   params = AllPublic.getParamsType(mActivity, "/getProduct", false);
        params.addParameter("categoryTwo",171);
        params.addParameter("currentPage",1);
        params.addParameter("pageSize", 4);
        Log.d("分类列表", "getJSON: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("分类列表：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        JSONArray records = jsonObject.getJSONArray("data");
                        Commodity commodity=null;

                        for (int i=0;i<records.length();i++){

                            commodity=new Commodity();
                            JSONObject object = records.getJSONObject(i);
                            String commodityid = object.has("id") ? object.getString("id") : "";//id
                            String image = object.has("productPicture") ? object.getString("productPicture") : "";//产品图片
                            String headLine = object.has("name") ? object.getString("name") : "";//产品名称
                            String tradeprice = object.has("wholesalePriceThree") ? object.getString("wholesalePriceThree") : "";//新价格-折扣价格
                            String originalprice = object.has("originalPrice") ? object.getString("originalPrice") : "";//原价-旧价格
                            String inventory = object.has("inventory") ? object.getString("inventory") : "";//商品库存-剩余库存
                            commodity.setCommodityID(commodityid);
                            commodity.setCommodityImg(image);
                            commodity.setCommodityName(headLine);
                            commodity.setPriceOld(originalprice);
                            commodity.setPriceNew(tradeprice);
                            commodity.setInventoryNumber(inventory);
                            mArrayListhuoniu.add(commodity);
                        }
                        handler.sendEmptyMessage(7);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                ex.printStackTrace();

            }
            @Override
            public void onCancelled(CancelledException cex) {


            }
            @Override
            public void onFinished() {


            }
        });
    }
    private void loadDatahuoniu() {
        if (mAdapterhuoniu==null){
            mAdapterhuoniu=new MyAdaper<Commodity>(mArrayListhuoniu,R.layout.item_com_zhuangong) {
                @Override
                public void bindView(ViewHolder holder, Commodity obj, int position) {
                    holder.setImageyuan(R.id.iv_CommodityImg,obj.getCommodityImg());//图片
                    holder.setText(R.id.iv_CommodityName,obj.getCommodityName());

                    if (isHuoNiu(mActivity)){
                        holder.setText(R.id.tv_priceNew,"￥"+obj.getPriceNew());
                        holder.setFlags(R.id.tv_priceOld,"￥"+obj.getPriceOld());
                    }else {
                        holder.setText(R.id.tv_priceNew,"￥?");
                        holder.setFlags(R.id.tv_priceOld,"￥?");
                    }
                }
            };
            mLoadListViewhuoniu.setAdapter(mAdapterhuoniu);
        }else {
            mAdapterhuoniu.notifyDataSetChanged();
        }
    }
}
